import { Server } from 'socket.io';
import { createServer } from 'http';
import express from 'express';
import { Game } from './api/Game';
import { logger } from './utils/logger';
import { ModLoader } from './mod/ModLoader';
import { register } from './register';

const app = express();
const httpServer = createServer(app);
const PORT = 3000;

const io = new Server(httpServer, {
	cors: {
		origin: '*',
		methods: ['GET', 'POST'],
	},
});

const game = new Game(io);
const Mod = new ModLoader();
register()

io.on('connection', (socket) => {
	socket.on('disconnect', () => {
		// 离开房间
		game.leaveRoom(socket.id);
	});

	socket.on('joinServer', (data: { roomId: string; playerName: string }) => {
		// 注册玩家
		game.addPlayer(socket.id, socket);
		// 设置名称
		game.setPlayerName(socket.id, data.playerName);
		// 创建房间
		game.addRoom(data.roomId, socket.id);
		// 加入房间
		game.joinRoom(data.roomId, socket.id);
	});

	// 选择部门
	socket.on('selectDept', (deptId: string) => {
		const room = game.getRoomByPlayerId(socket.id);
		if (!room) return;

		const dept = room.getDept(deptId);
		if (!dept || !dept.isAI) return;

		Object.values(room.depts).forEach((dept) => {
			if (dept.playerId == socket.id) {
				dept.playerId = dept.deptId;
				dept.isAI = true;
			}
		});

		// 选择部门
		dept.playerId = socket.id;
		dept.isAI = false;
		room.updateData();
		room.send('roomUpdate', {});
		logger.info(`SelectDept ${socket.id} ${deptId}`);
	});

	// 开始游戏
	socket.on('startGame', () => {
		const room = game.getRoomByPlayerId(socket.id);
		room?.start(socket);
	});

	// 打出卡牌
	socket.on('playCard', (data: { index: number; target: string }) => {
		const room = game.getRoomByPlayerId(socket.id);
		room?.playCard(socket.id, data.index, data.target);
	});

	socket.on('back', () => {
		// 离开房间
		game.leaveRoom(socket.id);
		// 返回主页
		socket.emit('showSection', '#main');
	});

	// 更新部门数据
	socket.on('deptUpdate', () => {
		const room = game.getRoomByPlayerId(socket.id);
		room?.updateDept();
	});
});

httpServer.listen(PORT, () => {
	logger.info(`RunServer: http://localhost:${PORT}`);
});
